package cool.webstudy.admin.utils;

import jakarta.servlet.http.HttpServletRequest;

/**
 *
 * @author 莫振双
 * @date 2024/8/25 21:38
 * @description: 请求工具
 */
public class RequestUtil {
    /**
     * @param request 请求信息
     * @return String ip信息
     * @description: 根据请求信息获取请求来源ip
     */
    public static String getRequestIp(final HttpServletRequest request) {
        String ip = request.getHeader("X-Real-IP");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");// 这是一个可以伪造的头
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        }
        // 最后一个为RemoteAddr
        int pos = ip.lastIndexOf(',');
        if (pos >= 0) {
            ip = ip.substring(pos);
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
        return ip;
    }
}
